'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 任务
 * @author sundbcn@gmail.com (sun debing)
 */

var async = require('async');
var Code = require('../../../consts/code');
var moduleType = require('../../../consts/moduleType');
var operationType = require('../../../consts/operationType');
var dataApi = require('../../../libs/dataApi');
var rewardService = require('../../../services/rewardService');
var missionService = require('../../../services/missionService');
var roleService = require('../../../services/roleService');
var PlayerManager = require('../../../libs/playerManager');
var missionConf = require('../../../config/missionConf');

module.exports = function (app) {
    return new Handler(app);
};

var Handler = function (app) {
    this.app = app;
};

/**
 * 获取任务奖励
 */
Handler.prototype.reward = function (msg, session, next) {
    var role_id = session.uid;
    var task_id = msg.task_id;
    var reward_item = {};
    if (!task_id) {
        return next(null, {
            code: Code.PARAM_ERROR
        });
    }

    var player_manager = new PlayerManager(role_id);
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['role', 'bag', 'build', 'soldier', 'task', 'achieve', 'daily_task', 'tech', 'accrued'],
                    cb
                );
            },
            function (cb) {
                var role_model = player_manager.role;
                var task_model = player_manager.task;

                if (!task_model.rewardTask(task_id)) {
                    return next(null, {
                        code: Code.TASK_REWARD_ERROR
                    });
                }

                reward_item = missionConf.getNewMissionRewardConf(role_model.getJob(), task_id);
                rewardService.addRewardListToRole(player_manager, reward_item, moduleType.receiveSalary, operationType.OPR_ACT_MAIN_TASK_REWARD);
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK,
                result: {
                    reward_list: reward_item
                }
            });
        }
    );
};
